package com.battery.eason.config;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.battery.eason.pojo.SysUser;
import com.battery.eason.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * JWT登录授权过滤器
 *
 * @author HuangSiYuan
 * @since 2021-06-07
 */

public class JwtAuthencationTokenFilter extends OncePerRequestFilter {

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    /**
     * 相当于前置拦截
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        /*首先获取token请求头*/
        String authHeader = request.getHeader(tokenHeader);
        /*给请求头判空,判断是否存在,如果存在的话就说明有token令牌*/
        /*startsWith()方法一般用于检测某请求字符串是否以指定的前缀开始的。*/
        /*请求头的存在形式为: tokenHead + 空格 + token令牌 */
        HttpSession session = request.getSession();
        if (null != authHeader && authHeader.startsWith(tokenHead)) {
            String authToken = authHeader.substring(tokenHead.length());
            /*通过token获取用户名*/
            String username = jwtTokenUtil.getUserNameFromToken(authToken);
            // token存在用户名但未登录,因为当我们登录或注册成功之后会在session里面添加上所有的用户信息
            if (null != username && null == session.getAttribute(username)) {
                //说明用户名为空而且session里面没有信息
                //进行登录
                //通过用户名查询用户信息, 然后更新到session里面去
                SysUser sysUser = sysUserService.getSysUserByUsername(username);
                //判断Token是否失效, 如果失效了的化就更新数据到session里面去
                if (jwtTokenUtil.validateToken(authToken,sysUser)) {
                    session.setAttribute(username,sysUser);
                }
            }
        }
        chain.doFilter(request,response);
    }
}